package upload

import (
	"context"
	"mime/multipart"
	"net/http"

	"github.com/blog-zero/api/admin/internal/common/errorx"
	"github.com/blog-zero/api/admin/internal/svc"
	"github.com/blog-zero/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
)

type UploadFileListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewUploadFileListLogic(r *http.Request, ctx context.Context, svcCtx *svc.ServiceContext) *UploadFileListLogic {
	return &UploadFileListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *UploadFileListLogic) UploadFileList() (*types.UploadFileListResp, error) {
	err1 := l.r.ParseMultipartForm(10 << 20) // 设置最大内存限制
	if err1 != nil {
		logc.Errorf(l.ctx, "设置最大内存限制,异常:%s", err1.Error())
		return nil, errorx.NewDefaultError("设置最大内存限制失败")
	}
	// 获取上传的文件
	files := l.r.MultipartForm.File["file"]
	fileContentTypes := l.r.Form["contentType"]
	// 验证文件和Content-Type的数量是否一致
	if len(files) != len(fileContentTypes) {
		return nil, errorx.NewDefaultError("文件数量和Content-Type的数量不一致")
	}
	// 处理每个文件和其Content-Type
	inputs := make(map[*multipart.FileHeader]string)
	for i, fileHeader := range files {
		// 获取文件的Content-Type
		contentType := fileContentTypes[i]
		inputs[fileHeader] = contentType
	}

	resp, err2 := l.svcCtx.Minio.UploadFileList(l.r.Context(), inputs)

	if err2 != nil {
		logc.Errorf(l.ctx, "上传minio失败,异常:%s", err2.Error())
		return nil, errorx.NewDefaultError("上传minio失败")
	}

	return &types.UploadFileListResp{
		Code:    "000000",
		Message: "上传图片成功",
		Data:    resp,
	}, nil
}
